package bean.persistence;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

public class PersistenceHelper {
	private PersistenceManager pm;
	private Query query;
	
	public void openPersistence() {
		pm = PMF.get().getPersistenceManager();
	}
	
	@SuppressWarnings("rawtypes")
	public void openQuery(Class queryClass) {
		query = pm.newQuery(queryClass);
	}
	
	public <T> T insert(T insertObj) {
		return pm.makePersistent(insertObj);
	}
	
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public Object getById(Class objClass, long id) {
		return pm.getObjectById(objClass, id);
	}
	
	public Object query(String filter, String order, String range, String declareParams, Object[] params) {
		if (filter != null)
			query.setFilter(filter);
		if (order != null)
			query.setOrdering(order);
		if (range != null)
			query.setRange(range);
		if (declareParams != null)
			query.declareParameters(declareParams);
		
		if (params == null)
			return query.execute();
		else
			return query.executeWithArray(params);
	}
	
	public <T> void delete(T delObj) {
		pm.deletePersistent(delObj);
	}
	
	public void closeQuery() {
		query.closeAll();
	}
	
	public void closePersistence() {
		pm.close();
	}
}
